<?php
namespace Home\Controller;
use Think\Controller;
header("Content-type: text/html; charset=utf-8"); 
class AdController extends CommonController {

  


	//添加图片广告页面
	public function index()
	{
		//每次进入检索所有广告是否有过期的
		check_ad_time();

		$user_id = session('uid');
		$file="./App/Common/Conf/config.php"; //全局配置
		$config = include $file;
		if($user_id<=0){
			$this->error('请先登陆再进行该操作。',U('Login/login'));
		}
		
		//查找用户级别
		$vip = $this->cheackvip($user_id);
		if($vip < 1){
			$this->error('只有vip1或者以上的用户才能发布广告。');
		}
		$kw = I('kws');
		$position = I('position');
		//检查热词广告状态
		$adcheck = $this->cheackadd($user_id,$kw,$config['ad_num'],$position);

		if($adcheck == 1){
			$this->error('该热词下广告已满'.$config['ad_num'].'个。');
		}elseif($adcheck == 2){
			$this->error('您在该热词下已经发布过一个广告。');
		}elseif($adcheck == 3){
			$this->error('不存在该热词。');
		}elseif($adcheck == 5){
			$this->error('请选择正确得广告位。');
		}elseif($adcheck == 6){
			$this->error('该广告位下已有广告。');
		}

		$this->assign('kw',$kw);  //把值赋给前台模板
		$this->assign('position',$position);  //把值赋给前台模板
		$this->assign('max_day',$config['buy_most']);  //把值赋给前台模板
		$this->display();
	}

	public function add()
	{
		$user_id = session('uid');
		$file="./App/Common/Conf/config.php"; //全局配置
		$config = include $file;
		$data = array();
		$paydata = array();
		if($user_id<=0){
			$this->error('请先登陆再进行该操作。',U('Login/login'));
		}
		//查找用户级别
		$vip = $this->cheackvip($user_id);
		if($vip < 1){
			$this->error('只有vip1或者以上的用户才能发布广告。');
		}
		
		//获取参数
		if(IS_POST){
			$kw = I('kw');
			$position = I('position');
			if(empty($kw)){
				$this->error('不存在该热词。');
			}
			//检查热词广告状态
			$adcheck = $this->cheackadd($user_id,$kw,$config['ad_num'],$position);
			if($adcheck == 1){
				$this->error('该热词下广告已满'.$config['ad_num'].'个。');
			}elseif($adcheck == 2){
				$this->error('您在该热词下已经发布过一个广告。');
			}elseif($adcheck == 3){
				$this->error('不存在该热词。');
			}elseif($adcheck == 5){
			$this->error('请选择正确的广告位。');
			}elseif($adcheck == 6){
				$this->error('该广告位下已有广告。');
			}
			$data['title']    = I('title');
			$paydata['buytime']    = I('addday');
			$data['img_link']    = I('img_link');
			$img_link     = I('img_link');
			$upload = new \Think\Upload();// 先实例化上传类 
			$upload->maxSize   = 3145728 ;// 设置附件上传大小 
			$upload->exts      = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型    
			$upload->savePath  = './slink/'; // 设置附件上传目录  
			$upload->rootPath  = './Upload/';
			// 上传文件     
			$info   =   $upload->upload();  
			$path =date("Y-m-d");
			$img_upload="$path/".$info['img_upload']['savename'];
			
			if(!$data['title']){
				$this->error('请填写广告标题。');
			}
			
			if($paydata['buytime']<=0){
				$this->error('请输入广告投放天数。');
			}
			
			if($paydata['buytime']>$config['buy_most']){
				$this->error('广告投放天数最多为'.$config['buy_most'].'天。');
			}
			
			if(!empty($data)){
				$data['img_url'] = $img_upload;
			}elseif(!empty($img_link)){
				$data['img_url'] = $img_link;
			}else{
				$this->error('请上传图片或者填写图片远程链接。');
			}
			
			$data['add_time'] = time();//发布时间
			$data['type'] = 1;//默认状态是下架
			$data['position'] = $position;//默认状态是下架
			$data['uid'] = $user_id;//用户ID
			$Cate = D('cate');
			$cat_id = $Cate->where("name='$kw'")->field('id')->select();

			$data['cat_id'] = $cat_id[0]['id'];//热词分类ID
			$data['cat_name'] = $kw;//热词分类名
			$data['ad_link'] = I('ad_link');//热词分类名
			$paydata['pay_code'] = I('pay_code');//热词分类名
			
			$price = $config['ad_price']*$paydata['buytime'];
			
			if($paydata['pay_code'] == 1){
				//如果是余额支付检查用户余额是否充足
				if(!$this->cheackye($user_id,$price)){
					$this->error('您的余额不足，支付失败。');
				}
			}
			
			$Ad = D('s_ad');
			if($Ad->create($data)){
				//写入购买记录表
				if($Ad->add()){
					$Payaccount = D('pay_account_log');
					$paydata['order_id'] = $Ad->getLastInsID();
					$paydata['uid'] = $user_id;
					$paydata['money'] = $price;
					$paydata['pay_type'] = 2;
					$paydata['type'] = 1;
					$paydata['add_time'] = time();
					$paydata['pay_status'] = 0;
					
					if($paydata['pay_code'] == 1){
						$paydata['pay_status'] = 1;
						$paydata['pay_time'] = time();
					}
					
					$Payaccount->create($paydata);
					$Payaccount->add();
					$payid = $Payaccount->getLastInsID();
					
					if($paydata['pay_code'] == 1){
						$this->account_change($user_id,$price,'用户发布广告。');
						$this->buy_success($paydata,1);
					}
					
					$this->success('发布成功',U('Search/index',array('kws'=>$kw)));
				}
			}
			
		}else{
			$this->error('参数错误，请重新发布。');
		}
	}
	
	public function edit()
	{
		$user_id = session('uid');
		$file="./App/Common/Conf/config.php"; //全局配置
		$config = include $file;
		$data = array();
		$paydata = array();
		if($user_id<=0){
			$this->error('请先登陆再进行该操作。',U('Login/login'));
		}
		//查找用户级别
		$vip = $this->cheackvip($user_id);
		if($vip < 1){
			$this->error('只有vip1或者以上的用户才能发布广告。');
		}

		//获取参数
		if(IS_POST){
			
			//$kw = I('kw');
			$ad_id = I('ad_id');
			//$position = I('position');
			
			/* if(empty($kw)){
				$this->error('不存在该热词。');
			} */
			if($ad_id<=0){
				$this->error('请选择要续费的广告。');
			}
			//检查热词广告状态
			$adcheck = $this->cheackedit($user_id,$config['ad_num'],$ad_id);
			
			if($adcheck == 1){
				$this->error('该热词下广告已满'.$config['ad_num'].'个。');
			}elseif($adcheck == 2){
				$this->error('您在该热词下已经发布过一个广告。');
			}elseif($adcheck == 3){
				$this->error('不存在该热词。');
			}elseif($adcheck == 5){
			$this->error('请选择正确的广告位。');
			}elseif($adcheck == 6){
				$this->error('该广告位下已有广告。');
			}elseif($adcheck == 7){
				$this->error('该广告已下架不能续费。');
			}elseif($adcheck == 8){
				$this->error('该广告不属于您。');
			}elseif($adcheck == 9){
				$this->error('不存在该广告。');
			}elseif($adcheck == 11){
				$this->error('该广告已下架，不能续费。');
			}
			
			//$data['title']    = I('title');
			$paydata['buytime']    = I('addday');
			//$data['img_link']    = I('img_link');
			//$img_link     = I('img_link');
			//$upload = new \Think\Upload();// 先实例化上传类 
			//$upload->maxSize   = 3145728 ;// 设置附件上传大小 
			//$upload->exts      = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型    
			//$upload->savePath  = './slink/'; // 设置附件上传目录  
			//$upload->rootPath  = './Upload/';
			// 上传文件     
			//$info   =   $upload->upload();  
			//$path =date("Y-m-d");
			//$img_upload="$path/".$info['img_upload']['savename'];
			
			/* if(!$data['title']){
				$this->error('请填写广告标题。');
			} */
			
			/* if($paydata['buytime']<=0){
				$this->error('请输入广告投放天数。');
			} */
			$Ad = D('s_ad');
			$ad_info = $Ad->where("ad_id=$ad_id")->find();
			$now = time();
			if($ad_info['end_time'] > $now){
				$last_time = $ad_info['end_time']-$now;
			}else{
				$last_time = 0;
			}
			
			$sum_time = $last_time+($paydata['buytime']*24*3600);
			$day = ceil($sum_time/24/3600); 

			if($day>$config['buy_most']){
				$this->error('广告投放天数最多为'.$config['buy_most'].'天。');
			}
			
			/* if(!empty($data)){
				$data['img_url'] = $img_upload;
			}elseif(!empty($img_link)){
				$data['img_url'] = $img_link;
			}else{
				$this->error('请上传图片或者填写图片远程链接。');
			} */
			
			$data['add_time'] = time();//发布时间
			//$data['type'] = 1;//默认状态是下架
			//$data['position'] = $position;//默认状态是下架
			//$data['uid'] = $user_id;//用户ID
			//$Cate = D('cate');
			//$cat_id = $Cate->where("name='$kw'")->field('id')->select();

			//$data['cat_id'] = $cat_id[0]['id'];//热词分类ID
			//$data['cat_name'] = $kw;//热词分类名
			//$data['ad_link'] = I('ad_link');//热词分类名
			$paydata['pay_code'] = I('pay_code');//支付方式
			
			$price = $config['ad_price']*$paydata['buytime'];

			if($paydata['pay_code'] == 1){
				//如果是余额支付检查用户余额是否充足
				if(!$this->cheackye($user_id,$price)){
					$this->error('您的余额不足，支付失败。');
				}
			}
			
				//更新记录表
				
				if($Ad->where(array('ad_id'=>$ad_id))->save($data)){
					$Payaccount = D('pay_account_log');
					$paydata['order_id'] = $ad_id;
					$paydata['uid'] = $user_id;
					$paydata['money'] = $price;
					$paydata['pay_type'] = 2;
					$paydata['type'] = 2;
					$paydata['add_time'] = time();
					$paydata['pay_status'] = 0;
					
					if($paydata['pay_code'] == 1){
						$paydata['pay_status'] = 1;
						$paydata['pay_time'] = time();
					}
					
					$Payaccount->create($paydata);
					$Payaccount->add();
					$payid = $Payaccount->getLastInsID();
					
					if($paydata['pay_code'] == 1){
						$this->account_change($user_id,$price,'用户续费广告。');
						$this->buy_success($paydata,2);
					}
					
					$this->success('续费成功',U('Person/myad'));
				}else{
					$this->error('续费失败',U('Person/myad'));
				}
			
		}else{
			$ad_id = I('ad_id');
			$this->assign('ad_id',$ad_id);  //把值赋给前台模板
			$this->assign('max_day',$config['buy_most']);  //把值赋给前台模板
			$this->display();
		}
	}
	
	
	
	//浏览量
	public function view(){
		$aid = !empty($_POST['aid'])? $_POST['aid'] : 0;
		$Ad = D('s_ad');
		$data = array();
		$data['error'] = 0;
		if($aid>0){
			$ainfo = $Ad->where("ad_id=$aid")->find();
			//更新浏览量
			$click_count = $ainfo['click_count'];
			$click_count++;
			M('s_ad')->where(array('ad_id'=>$aid))->save(array('click_count'=>$click_count));
			$data['url'] = $ainfo['ad_link'];
			$data['ad_id'] = $aid;
			$data['click_count'] = $click_count;
			
		}else{
			$data['error'] = 1;
		}
		
		$this->ajaxReturn($data);
	}
	
	//投诉
	public function complain(){
		$aid = !empty($_POST['aid'])? $_POST['aid'] : 0;
		$is_tousu = !empty($_POST['is_tousu'])? $_POST['is_tousu'] : 0;//如果是0代表要投诉，如果是1代表要取消投诉。
		$user_id = session('uid');
		//查找用户级别
		$data = array('error'=>0,'ad_id'=>$aid);
		
		if($user_id<=0){
			$data['error'] = 1;
			$data['msg'] = '请先登陆再进行该操作。';
			$this->ajaxReturn($data);
		}
		
		$vip = $this->cheackvip($user_id);
		
		if($vip < 1){
			$data['error'] = 1;
			$data['msg'] = '只有vip1或者以上的用户才能投诉。';
			$this->ajaxReturn($data);
		}
		$Ad = D('s_ad');
		$Cl = D('complain_log');
		
		if($aid>0){
			$ainfo = $Ad->where("ad_id=$aid")->find();
			$complain_count = $ainfo['complain_count'];
			//更新浏览量
			if($is_tousu == 0){
				$complain_count++;
			}else{
				$complain_count--;
			}
			M('s_ad')->where(array('ad_id'=>$aid))->save(array('complain_count'=>$complain_count));
			$data['complain_count'] = $complain_count;
			$data['is_tousu'] = $is_tousu;
			//处理投诉表
			$clinfo = $Cl->where("uid=$user_id AND aid=$aid")->find();
			if(!empty($clinfo)){
				if($is_tousu == 0){
					$Cl->where(array('id'=>$clinfo['id']))->save(array('status'=>1,'add_time'=>time()));
					$data['msg'] = '投诉成功';
				}else{
					$Cl->where(array('id'=>$clinfo['id']))->save(array('status'=>2,'add_time'=>time()));
					$data['msg'] = '取消投诉成功';
				}
			}else{
				if($is_tousu == 0){
					$data2 = array(
						'aid' => $aid,
						'uid' => $user_id,
						'add_time' => time(),
						'status' => 1
					);
					if($Cl->create($data2)){
						//写入购买记录表
						if($Cl->add()){
							$data['msg'] = '投诉成功';
						}
					}else{
						$data['msg'] = '投诉失败';
						$data['error'] = 1;
					}
				}else{
					$data['msg'] = '投诉失败';
					$data['error'] = 1;
				}
			}
		}else{
			$data['msg'] = '不存在该广告';
			$data['error'] = 1;
		}
		
		$this->ajaxReturn($data);
	}
	
	
	//检查vip是否足够
	public function cheackvip($user_id){
		$users =D('users');
		//查找用户级别
		if($user_id>0){
			$usersvip = $users->field('vip')->where(array('userid'=>$user_id))->find();
			return $usersvip['vip'];
		}
		return 0;
	}
  
	//判断该用户在此热词下是否已经发布过图片
	public function cheackadd($user_id,$kw,$num,$position){
		$Ad = D('s_ad');
		$Cate = D('cate');
		$time = time();
		if(!empty($kw)){
			$adcount = $Ad->join('cate ON cate.id = s_ad.cat_id')->where("cate.name='$kw' AND s_ad.type=2 AND s_ad.end_time > $time ")->count();
			if($adcount>=$num){
				return 1;//热词下的广告超过上限
			}
			$adcountuser = $Ad->join('cate ON cate.id = s_ad.cat_id')->where("cate.name='$kw' AND s_ad.uid = $user_id AND s_ad.type = 2 AND s_ad.end_time > $time")->count();
			
			if($adcountuser>=1){
				return 2;//用户只能在这个热词下发布一个广告
			}
			$catecount = $Cate->where("name='$kw'")->count();
			if($catecount<=0){
				return 3;//不存在的热词
			}
			if(empty($position)){
				return 5;//不存在这个广告位
			}else{
				$positioncount = $Ad->where("cat_name='$kw' AND s_ad.type=2 AND position = $position ")->count();
				if($positioncount>0){
					return 6;//广告位已经有广告存在
				}
			}
			return 4;
		}
		return 3;
	}
	
	//判断该用户在此热词下是否已经发布过图片
	public function cheackedit($user_id,$num,$ad_id){
		$Ad = D('s_ad');
		$Cate = D('cate');
		$now = time();
		//查询该广告是否过期
		$ad_info = $Ad->where("ad_id=$ad_id")->find();
		if(!empty($ad_info)){
			if($ad_info['uid']!=$user_id){
				return 8;//广告不属于此用户
			}
			if($ad_info['type'] == 1){
				return 11;
			}
			if($ad_info['end_time']>$now){
				//如果是未过期续费，直接放行
				if($ad_info['type']>1){
					return 10;
				}else{
					return 7;//下架不能续费
				}
			}else{
				//如果是过期续费，要验证重新发布
				return $this->cheackadd($user_id,$ad_info['cat_name'],$num,$ad_info['position']);
			}
		}else{
			return 9;
		}
	}
	
	
	//判断余额是否充足
	public function cheackye($user_id,$money){
		$users =D('users');
		//查找用户级别
		$usercmoney = $users->field('cmoney')->where(array('userid'=>$user_id))->select();
		if($usercmoney[0]['cmoney'] >= $money){
			return true;
		}else{
			return false;
		}
	}
	
	//处理购买成功后余额变动和广告状态时间变动
	public function account_change($user_id,$money,$desc){
		//扣除用户余额
		$userinfo=D('users');
		$where = array('userid'=>$user_id);
		$fields = array('cmoney');
		$userinfos = $userinfo->field($fields)->where($where)->find();

		/*扣除余额*/
		$new_money = $userinfos['cmoney'] - $money;

		M('users')->where(array('userid'=>$user_id))->save(array('cmoney'=>$new_money));
		/*写入日志*/
		$data = array(
			'user_id'=>$user_id,
			'money'=>(-1)*$money,
			'add_time'=>time(),
			'desc'=>$desc
			);
		M('user_account_log')->add($data);
		return true;
	}
	
	
	//处理购买成功后余额变动和广告状态时间变动
	public function buy_success($paydata,$type){
		$Ad = D('s_ad');
		$ad_info = $Ad->where("ad_id=$paydata[order_id]")->find();
		$now = time();
		if($type == 1){
			$end_time = $now+$paydata['buytime']*24*3600;
		}else{
			if($ad_info['end_time'] >$now){
				$end_time = $ad_info['end_time'] +$paydata['buytime']*24*3600;
			}else{
				$end_time = $now+$paydata['buytime']*24*3600;
			}
		}

		$Ad->where(array('ad_id'=>$paydata['order_id']))->save(array('end_time'=>$end_time,'type'=>2));
		return true;
	}
	
}
 